﻿namespace IOP.OpenType.Tables
{
    /// <summary>
    /// 
    /// </summary>
    public class CmapSubTable4 : CmapSubTable
    {
        /// <summary>
        /// 2 * segCount
        /// </summary>
        public ushort SegCountX2 { get; set; }
        /// <summary>
        /// 2 * (2**FLOOR(log2(segCount)))
        /// </summary>
        public ushort SearchRange { get; set; }
        /// <summary>
        /// log2(searchRange/2)
        /// </summary>
        public ushort EntrySelector { get; set; }
        /// <summary>
        /// (2 * segCount) - searchRange
        /// </summary>
        public ushort RangeShift { get; set; }
        /// <summary>
        /// Ending character code for each segment, last = 0xFFFF.
        /// </summary>
        public ushort[] EndCode { get; set; }
        /// <summary>
        /// This value should be zero
        /// </summary>
        public ushort ReservedPad { get; set; }
        /// <summary>
        /// Starting character code for each segment
        /// </summary>
        public ushort[] StartCode { get; set; }
        /// <summary>
        /// Delta for all character codes in segment
        /// </summary>
        public short[] IdDelta { get; set; }
        /// <summary>
        /// Offset in bytes to glyph indexArray, or 0
        /// </summary>
        public ushort[] IdRangeOffset { get; set; }

        /// <summary>
        /// 获取字形Id
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public override uint GetGlyphId(char c)
        {
            int ic = c;
            uint glyphIndex = 0;
            for (int i = 0; i < StartCode.Length; i++)
            {
                if (ic >= StartCode[i] && ic <= EndCode[i])
                {
                    if (IdRangeOffset[i] != 0)
                    {
                        int ind = ic - StartCode[i];
                        glyphIndex = IdRangeOffset[i + IdRangeOffset[i] / 2 + ind];
                        break;
                    }
                    else
                    {
                        glyphIndex = (uint)((IdDelta[i] + ic) & 0xffff);
                        break;
                    }
                }
            }
            return glyphIndex;
        }
        /// <summary>
        /// 获取最大有字形字符
        /// </summary>
        /// <returns></returns>
        public override char GetMaxCharacter()
        {
            ushort end = EndCode[^2];
            return (char)end;
        }
        /// <summary>
        /// 获取最小有字形字符
        /// </summary>
        /// <returns></returns>
        public override char GetMinCharacter()
        {
            ushort start = StartCode[0];
            return (char)start;
        }
    }
}
